<template>
  <div class="Spike">
    <div style="margin-bottom:50px">
      手动录题
      <el-switch
        v-model="changeStatus"
        active-color="#13ce66"
        inactive-color="#ff4949"
        style="margin:0px 20px"
      ></el-switch>上传Excel
    </div>
    <div>
      <el-form label-width="80px" :model="jobExam" :rules="rules" ref="jobExam">
        <!-- 手动导入题目 -->
        <template v-if="changeStatus==true">
          <!-- 岗位类型 -->
          <el-form-item label="岗位类型" prop="jobTypeId">
            <div class="block">
              <el-cascader
                v-model="jobExam.jobTypeId"
                :options="jobTypeOption"
                @change="handleChange"
                :props="jobTypeParams"
                :show-all-levels="true"
                @blur="jobTypeBlur"
              ></el-cascader>
            </div>
          </el-form-item>
          <!-- 技能类型 -->
          <el-form-item label="技能类型" prop="skillTypeId">
            <template>
              <el-select v-model="jobExam.skillTypeId" placeholder="请选择" @blur="skillTypeBlur">
                <el-option
                  v-for="skillType in skillTypeOptions"
                  :key="skillType.id"
                  :label="skillType.skillTypeName"
                  :value="skillType.id"
                ></el-option>
              </el-select>
            </template>
          </el-form-item>
          <!-- 题目类型 -->
          <el-form-item label="题目类型" prop="examTypeId">
            <el-cascader
              v-model="jobExam.examTypeId"
              :options="examTypeOptions"
              @change="handleChange"
              :props="examTypeParams"
              @blur="examTypeBlur"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="题目内容" prop="content">
            <el-input v-model="jobExam.content" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="选项A" prop="optionA">
            <el-input v-model="jobExam.optionA" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="选项B" prop="optionB">
            <el-input v-model="jobExam.optionB" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="选项C" prop="optionC">
            <el-input v-model="jobExam.optionC" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="选项D" prop="optionD">
            <el-input v-model="jobExam.optionD" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item label="题目答案" prop="answer">
            <el-input v-model="jobExam.answer" placeholder="请输入内容"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('jobExam')">提交</el-button>
            <el-button @click="resetForm('jobExam')">重置</el-button>
          </el-form-item>
        </template>
        <!-- Excel导入题目 -->
        <template v-if="changeStatus===false">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="http://localhost/backstage/jobExam/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :auto-upload="false"
            style="margin-bottom:50px"
            :headers="headerObj"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button
              style="margin-left: 10px;"
              size="small"
              type="success"
              @click="submitUpload"
            >上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传excel文件</div>
          </el-upload>
        </template>
      </el-form>
    </div>
  </div>
</template>

<script>
import axios from "axios";
let path = "http://localhost/backstage/jobExam";
export default {
  data() {
    var checkJobType = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("岗位类型不能为空"));
      }
      callback();
    };
    var checkSkillType = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("技能类型不能为空"));
      }
      callback();
    };
    var checkExamType = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("题目类型不能为空"));
      }
      callback();
    };
    var checkContent = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("标题不能为空"));
      }
      callback();
    };
    var checkOptionA = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("选项A不能为空"));
      }
      callback();
    };
    var checkOptionB = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("选项B不能为空"));
      }
      callback();
    };
    var checkOptionC = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("选项C不能为空"));
      }
      callback();
    };
    var checkOptionD = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("选项D不能为空"));
      }
      callback();
    };
    var checkAnswer = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("答案不能为空"));
      }
      callback();
    };
    return {
      //定义上传文件的请求头
      headerObj: {
        id: "AC123123123123"
      },
      changeStatus: "A",
      fileList: [],
      //岗位类型
      jobTypeOption: [],

      //技能类型
      skillTypeOptions: [],

      //题目类型
      examTypeOptions: [],

      jobExam: {
        jobTypeId: "",
        examTypeId: "",
        skillTypeId: "",
        content: "",
        optionA: "",
        optionB: "",
        optionC: "",
        optionD: "",
        answer: "",
        creationBy: "AC123414125235"
      },
      jobTypeParams: {
        label: "jobTypeName",
        children: "children",
        value: "id",
        checkStrictly: true,
        emitPath: false
      },
      examTypeParams: {
        label: "examTypeName",
        children: "children",
        value: "id",
        checkStrictly: true,
        emitPath: false
      },
      //表单检查规则
      rules: {
        jobTypeId: [{ validator: checkJobType, trigger: ["change", "blur"] }],
        skillTypeId: [
          { validator: checkSkillType, trigger: ["change", "blur"] }
        ],
        examTypeId: [{ validator: checkExamType, trigger: ["change", "blur"] }],
        content: [{ validator: checkContent, trigger: "blur" }],
        optionA: [{ validator: checkOptionA, trigger: "blur" }],
        optionB: [{ validator: checkOptionB, trigger: "blur" }],
        optionC: [{ validator: checkOptionC, trigger: "blur" }],
        optionD: [{ validator: checkOptionD, trigger: "blur" }],
        answer: [{ validator: checkAnswer, trigger: "blur" }]
      }
    };
  },
  methods: {
    // turnStatus() {
    //   if (this.changeStatus == "A") {
    //     changeStatus = "B";
    //   } else {
    //     changeStatus = "A";
    //   }
    // },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    //岗位类型选择器失去焦点验证
    jobTypeBlur() {
      this.$refs.jobExam.validateField("jobTypeId");
    },
    //技能类型选择器失去焦点验证
    skillTypeBlur() {
      this.$refs.jobExam.validateField("skillTypeId");
    },
    //题目类型选择器失去焦点验证
    examTypeBlur() {
      this.$refs.jobExam.validateField("examTypeId");
    },

    warningMessage(info) {
      this.$message({
        message: info,
        type: 'warning'//success、warning
      });
    },
    successMessage(info) {
      this.$message({
        message: info,
        type: 'success'//success、warning
      });
    },
    errorMessage(info) {
      this.$message.error(info);
    },

    //提交表单
    submitForm(formName) {
      this.jobExam.creationBy=JSON.parse(localStorage.getItem("account")).id;
      
      this.$refs[formName].validate(valid => {
        if (valid) {
          axios({
            method: "post",
            url: path + "/jobExam",
            data: this.jobExam,
            headers: {
              id: JSON.parse(localStorage.getItem("account")).id,
              token: JSON.parse(localStorage.getItem("account")).token
            }
          })
            .then(res => {
              console.log(res.data);
              if (res.data.code === 500) {
                this.warningMessage("你未有权限!")
              } else if (res.data.code === 10100) {
                this.successMessage("添加题目成功!")
                this.$refs[formName].resetFields();
              } else {
                this.errorMessage("添加题目失败!")
              }
            })
            .catch(error => {
              this.errorMessage("添加错误!")
              console.log(error);
            });
        } else {
          this.warningMessage("请填写完整的题目信息!")
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    listAllJobType() {
      axios({
        method: "GET",
        url: path + "/jobType",
        headers: {
          id: JSON.parse(localStorage.getItem("account")).id,
          token: JSON.parse(localStorage.getItem("account")).token
        }
      })
        .then(res => {
          console.log(res.data.data);
          // this.jobTypeOption = res.data.data;
          this.jobTypeOption = this.getTreeData(res.data.data);
        })
        .catch(error => {
          console.log(error);
        });
    },
    listAllSkillType() {
      axios({
        method: "GET",
        url: path + "/skillType",
        headers: {
          id: JSON.parse(localStorage.getItem("account")).id,
          token: JSON.parse(localStorage.getItem("account")).token
        }
      })
        .then(res => {
          console.log(res.data.data);
          // this.jobTypeOption = res.data.data;
          this.skillTypeOptions = res.data.data;
        })
        .catch(error => {
          console.log(error);
        });
    },
    listAllExamType() {
      axios({
        method: "GET",
        url: path + "/examType",
        headers: {
          id: JSON.parse(localStorage.getItem("account")).id,
          token: JSON.parse(localStorage.getItem("account")).token
        }
      })
        .then(res => {
          console.log(res.data.data);
          // this.jobTypeOption = res.data.data;
          this.examTypeOptions = this.getTreeData(res.data.data);
        })
        .catch(error => {
          console.log(error);
        });
    },
    handleChange(type) {
      console.log(type);
    },
    // 递归消除空数组
    getTreeData(data) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    }
  },
  created() {
    this.listAllJobType();
    this.listAllSkillType();
    this.listAllExamType();
  }
};
</script>

<style scoped>
.Spike {
  width: 500px;
  min-height: 100%;
  padding: 15px;
  box-sizing: border-box;
}
</style>